package com.example.work12.adapter;

import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.work12.R;
import com.example.work12.bean.Music;
import com.example.work12.utils.MusicUtils;

import java.util.List;

public class MusicAdapter extends BaseAdapter {
    private List<Music> list;
    private Context context;

    public MusicAdapter(List<Music> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if(convertView == null){
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.list_layout,null);
            viewHolder.pic = convertView.findViewById(R.id.pic);
            viewHolder.name = convertView.findViewById(R.id.name);
            viewHolder.song = convertView.findViewById(R.id.song);
            viewHolder.time = convertView.findViewById(R.id.time);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(list.get(position).getData());
        byte[] picture = retriever.getEmbeddedPicture();
        Glide.with(context).load(picture).into(viewHolder.pic);

        viewHolder.name.setText(list.get(position).getName());
        viewHolder.song.setText(list.get(position).getArtist());
        viewHolder.time.setText(MusicUtils.formatTime(list.get(position).getDuration()));
        return convertView;
    }

    class ViewHolder{
        ImageView pic;
        TextView name,song,time;
    }
}
